const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
// log工具
const logUtil = require('./utils/logUtil')

const index = require('./routes/index')
const user = require('./routes/user')

// error handler
onerror(app)

// middlewares post运行的关键
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger()) // 日志输出
app.use(require('koa-static')(__dirname + '/public')) // 后端静态资源

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// try-catch 中间件
app.use(async (ctx, next) => {
  const start = new Date()
  let ms
  try {
    await next()
    // 注意打印顺序
    logUtil.logResponse(ctx)
  } catch (err) {
    ms = new Date() - start
    logUtil.logError(ctx, err, ms)
    ctx.throw(err.status || 500, err.message, {expose: true})
  }
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(user.routes(), user.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
